package com.hzsai.nettylearn.server;

import com.hzsai.nettylearn.util.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * hzsai 2019/11/15
 * usage:
 **/
@Component
public class FakeAsyncTimeServer {


    private static final Logger logger = LoggerFactory.getLogger(TimeServer.class);

    @Value("${timeserver.port:1048}")
    private int port;

    @Value("${timeserver.ip:127.0.0.1}")
    private String ip;

    private ServerSocket server = null;

    private boolean runnable = true;

    private int poolSize = 50;
    private int queueSize = 10000;

    /**
     * 执行线程池
     */
    private FakeAsyncTimeThreadPoolExecutor executor;

    @PostConstruct
    public void postConstruct() throws IOException {

        logger.info(DateTimeUtil.getDate() + "Server: Fake Async TimeServer starting...");
        server = new ServerSocket(port, 5, InetAddress.getByName(ip));
        executor = new FakeAsyncTimeThreadPoolExecutor(poolSize, queueSize);
    }

    public void start() throws IOException {

        logger.info(DateTimeUtil.getDate() + "Server: Running...");
        while (runnable) {
            Socket socket = server.accept();
            logger.info(DateTimeUtil.getDate() + "Server: Client from 【{}】 connected.",
                    socket.getInetAddress().getHostAddress()  + ":"+ String.valueOf(socket.getPort()));
            Thread t = new Thread(new TimeServerHandler(socket));
            executor.execute(t);
        }
    }

    /**
     * 断开连接后，在exector里面的任务将继续进行
     * @throws IOException
     */
    public void stop() throws IOException {

        if (server != null)
            server.close();
    }

}
